package com.mti.ftp.factory;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Log4j2
@Service
public class FtpClientFactory {

    @Value("${ftp.server}")
    private String server;
    @Value("${ftp.port}")
    private int port;
    @Value("${ftp.username}")
    private String user;
    @Value("${ftp.password}")
    private String password;

    /**
     * 创建并配置 FTPClient 实例
     *
     * @return 配置好的 FTPClient 实例
     * @throws IOException 如果连接失败或配置错误
     */
    public FTPClient createFtpClient() throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            // 连接到 FTP 服务器
            ftpClient.connect(server, port);
            if (!ftpClient.login(user, password)) {
                throw new IOException("登录 FTP 服务器失败: " + server);
            }

            // 设置字符编码为 UTF-8
            ftpClient.setControlEncoding("UTF-8");

            // 设置传输模式为二进制
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();

            log.info("成功连接到 FTP 服务器: {}", server);
            return ftpClient;
        } catch (IOException e) {
            disconnect(ftpClient);
            throw new IOException(e);
        }
    }

    /**
     * 断开 FTPClient 连接
     *
     * @param ftpClient FTPClient 实例
     */
    public void disconnect(FTPClient ftpClient) {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
                log.info("已断开 FTP 服务器连接");
            } catch (IOException ex) {
                log.error("断开 FTP 连接时发生错误", ex);
            }
        }
    }
}
